package com.benyi.byiee.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.benyi.byiee.constants.Role;
import com.benyi.byiee.constants.UserType;
import com.benyi.byiee.model.api.User;
import com.benyi.byiee.model.db.UserAccount;
import com.benyi.byiee.util.HttpFileUtil;
import com.benyi.byiee.util.OnlineUserList;
import com.benyi.util.Config;
import com.benyi.util.JsonResult;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
@RequestMapping("/file")
public class FileRest {
	
	private static Logger log = LoggerFactory.getLogger(FileRest.class);
	
	private static String DOWN_PREFIX="/file/dn/";
	private static final int MAX_FILE_QTY = 5000; //每个目录下的最多文件数(目录数)
	@Resource(name="config")
	private Config config; 
 
        
    @Role(value=UserType.ALL)
    @RequestMapping(value = "/up/{ctype}", method = RequestMethod.POST,consumes = {"multipart/form-data"})
    public JsonResult<String> uploadFile( @PathVariable("ctype") String cType, @RequestHeader(value = "token") String token,
    		@RequestParam("file") MultipartFile file) {
    	JsonResult<String> ret ;
        if (file.isEmpty()) {
        	ret = JsonResult.fail("Fail");
            return ret;
        }
        
        User user = OnlineUserList.getUser(token); 
        if(user == null) {
        	ret = JsonResult.fail("Fail");
        	ret.setDesc("not login");
            return ret;
        }   
        
        String dir = config.get("file_dir"); 
        while(dir.indexOf("/") >=0  && File.separator == "\\") {
        	dir = dir.replace("/", File.separator);
        } 
        UserAccount ua = user.getAccount();
        
        String child = getDirectory(ua.getRid(),user.getCurrentCompany(),cType);
        
        if(child==null) {
        	ret = JsonResult.fail("WRONG_TYPE", "无效的内容类别");
        	return ret;
        }
    	
        String subDir = dir + File.separator + cType + File.separator + child; 
    	
        File sub = new File(subDir);
        if(sub.exists() == false) {
        	sub.mkdirs();
        }
        
        String fileName = getFileName(ua.getRid(),0,cType,file.getOriginalFilename()); 
        File dest = new File(sub, fileName);
        
        log.debug("Save to file，path:{},File:{}",subDir,fileName);
        
        try {
            file.transferTo(dest); // 将上传的文件保存到目标文件 
            //ret = JsonResult.success(child + File.separator + fileName, "sucess");
            fileName = child + "/" + fileName ;
            
            while(fileName.indexOf("\\") >=0 ) {
            	fileName = dir.replace("\\", "/");
            }             
            ret = JsonResult.success(fileName, "sucess");
            return ret;
        } catch (IOException e) {
        	log.error("save file exception", e);
            e.printStackTrace(); 
        }
        ret = JsonResult.fail("Fail");
        return ret;
    }
    
    private String getDirectory(long userId,long comId,String type) {
    	 
    	String child=null;
    	long sid = userId;
    	 
    	if(type.equals("uicon")) {//用户头像
    		sid = userId;  
    	}else {
    		sid = comId;
    		if(type.equals("clogo")) { //企业logo  
    			child=null; //
    		}else
    		if(type.equals("sweb")) {  //静态web文件,分组后，每个企业一个目录，文件名保持不变
    			child = String.valueOf(comId); 
    		}else 
    		if(type.equals("tweb")) {  //模板建站 ,分组后，每个企业一个目录，文件名保持不变
    			child = String.valueOf(comId); 
        	}else {
        		return null;
        	}
    	} 
    	
    	String sub = String.valueOf(sid / MAX_FILE_QTY + 1) ;
    	if(child != null ) {
    		sub = sub + File.separator + child;  
    	} 
    	return sub;
    }
    
    private String getFileName(long userId,long comId,String type,String name) {
    	
    	String fileName=name;
    	int index = name.lastIndexOf(".");
    	String extName = name.substring(index);
    	if(type.equals("uicon")) {//用户头像
    		fileName = String.valueOf(userId) + extName;
    	}else { 
    		if(type.equals("clogo")) { //企业logo 
    			fileName = String.valueOf(comId) + extName; 
    		}else
    		if(type.equals("sweb")) {  //静态web文件
    			//保持不变
    		}else 
    		if(type.equals("tweb")) {  //模板建站
    			//保持不变
        	} 
    	} 
    	return fileName;
    }
    
    @RequestMapping(value = "/dn/{ctype}/**", method = RequestMethod.GET)
    public void downFile( @PathVariable("ctype") String cType , HttpServletRequest request,HttpServletResponse res) {
    	String uri = request.getRequestURI();   
    	
    	System.out.println("request URI:"+uri);
    	
    	String dir = config.get("file_dir");   
        int index = uri.indexOf(DOWN_PREFIX);
        
    	String fileName=null;
    	if(index>=0) {
    		fileName = uri.substring(index+DOWN_PREFIX.length());
    	}else {
    		return;
    	}   
    	
        File file = new File(dir,fileName);
        
        System.out.println("file path:"+file.getAbsolutePath() );
        
        if(file.exists()==false) {
        	log.info("目录：{}中文件:{}不存在",dir,fileName);
        	notExist(res,"resource is not exist[D]!"); 
        	return;
        }
        if(file.isDirectory()) {
        	File f = new File(file,"index.htm");
        	if(f.exists() == false) {
        		f = new File(file,"index.html");
        		if(f.exists()==false) {
        			notExist(res,"resource is not exist[F]!"); 
                	return;
        		}
        	}
        	file = f;
        	String to;
        	if(uri.endsWith("/")==true) {
        		to = uri + f.getName();
        	}else {
        		to = uri + "/" + f.getName();
        	}
        	try { 
        		res.sendRedirect(to);
        	}catch(Exception e) {
        		log.error("sendRedirect:{} exception:{}",to, e);
            	showException(res,e);
        	} 
        	return;
        }
        
        try {
        	HttpFileUtil.writeFile(res, file);
        }catch(Exception e) {
        	log.error("get file fail:{},exception:{}",fileName,e);
        	showException(res,e);
        } 
    }
    
    private void showException(HttpServletResponse res, Exception e) {
    	try {
    		res.setCharacterEncoding(HttpFileUtil.DEFAULT_CODE);
    		PrintWriter out = res.getWriter();
    		e.printStackTrace(out);
    		out.flush();
    	}catch(Exception e1) {
    		log.error("write exception failed",e);
    	}
    }
    
    private void notExist(HttpServletResponse res,String msg) {
    	try {
    		res.setHeader("Content-Type", "text/html;charset=UTF-8");
    		res.setStatus(HttpStatus.NOT_FOUND.value()); 
    		res.setCharacterEncoding("UTF-8");
    		PrintWriter out = res.getWriter(); 
    		out.write(msg);
    		out.flush(); 
    	}catch(Exception e1) {
    		//
    	}
    }
    
}

